﻿/*
 * Copyright by Marek Brun
 * 
 * Licensed under the MOZILLA PUBLIC LICENSE, Version 1.1 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *	  http://www.mozilla.org/MPL/MPL-1.1.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
var ignored='Flash UI Components,Component Assets,COMPONENTS'.split(',');
var isIntPositions=true;
var isLayerRename=true;
var isDeleteEmptyFolders=true;

/*

Class StructureItem {
	
	var name:String;
	var parent:StructureItem;
	var childs:Array; //of StructureItem
	var libraryItem:LibraryItem;
	var usedCount:uint;
	var lowestLevel:uint;
	
}

Class FolderItem {
	
	var name:String;
	var childsCount:uint;
	
}

*/

//---------------------------------------------FUNCTIONS--------------------------
getTabs=function(num){
	var arr=[]
	for(var i=0;i<num;i++){
		arr.push('	');
	}
	return arr.join('');
}

getStructure=function(tl){
	libraryItems={};
	return getStructureItem(tl, null, 0);
}

getStructureItem=function(tl, parent, level){
	if(!tl){
		fl.trace("!tl:"+tl+'  parent:'+parent.name);
		return [];
	}
	var objs=[], objsBeen={}, layer, structureItem, item, isOneElementLayer, layerElements, layerItemsAsoc;
	var layersSum=tl.layers.length, elements;
	for(var i=0,j,n;i<layersSum;i++){
		layer=tl.layers[i];
		isOneElementLayer=true;
		layerElements=[];
		layerItemsAsoc={};
		for(j=0;j<tl.layers[i].frameCount;j++){
			elements=tl.layers[i].frames[j].elements;
			for(n=0;n<elements.length;n++){
				if(isIntPositions){
					if(elements[n].elementType!='shape' && elements[n].elementType!='shapeObj'){
						elements[n].x=Math.round(elements[n].x);
						elements[n].y=Math.round(elements[n].y);
					}
				}
				if(!elements[n].libraryItem){  continue; }
				if(!layerItemsAsoc[elements[n].libraryItem.name]){
					layerItemsAsoc[elements[n].libraryItem.name]=true;
					layerElements.push(elements[n]);
				}
				if(!objsBeen[elements[n].libraryItem.name]){
					objsBeen[elements[n].libraryItem.name]=true;
					
					if(libraryItems[elements[n].libraryItem.name]){
						structureItem=libraryItems[elements[n].libraryItem.name];
						structureItem.usedCount++;
						if(level<structureItem.lowestLevel){
							structureItem.lowestLevel=level;
							structureItem.assetsParent=parent;
						}
						continue;
					}
					
					structureItem={};
					structureItem.libraryItem=elements[n].libraryItem;
					structureItem.name=getName(elements[n].libraryItem.name);
					
					libraryItems[elements[n].libraryItem.name]=structureItem;
					structureItem.lowestLevel=level;
					structureItem.assetsParent=parent;
					
					structureItem.usedCount=1;
					if(parent){ structureItem.parent=parent; }
					if(elements[n].libraryItem.timeline){
						structureItem.childs=getStructureItem(elements[n].libraryItem.timeline, elements[n].libraryItem, level+1);
					}else{
						structureItem.childs=[];
					}
					objs.push(structureItem);
				}
			}
		}
		if(isLayerRename && layerElements.length==1){
			if(layerElements[0].name){
				layer.name='.'+layerElements[0].name;
			}else if(layerElements[0].elementType=='instance'){
				layer.name=getName(layerElements[0].libraryItem.name);
			}else{
				layer.name='('+layerElements[0].elementType+')';
			}
		}
	}
	if(parent){
		return objs;
	}
	return {
		name:'root',
		childs:objs
	}
}

getName=function(name){
	var arr=name.split('/');
	return arr[arr.length-1];
}

getFolder=function(name){
	var arr=name.split('/');
	arr.pop();
	return arr.join('/');
}

getStructureFolder=function(item){
	if(item.parent){
		return getStructureFolder(item.parent)+'/'+item.name+' gfx/'+item.name
	}
	return item.name;
}

prepareNames=function(folders, item){
	if(item.usedCount>1){
		folders.pop();
		folders.push('shared');
	}
	item.libName=folders.join('/')+'/'+item.name;
	item.libName=item.libName.split('shared/shared').join('shared');
	item.libName=item.libName.split('root/').join('');
	
	folders.push(item.name+' ');
	for(var i=0;i<item.childs.length;i++){
		prepareNames(folders.concat(), item.childs[i]);
	}
	
	
}

traceObj=function(obj){
	for(var v in obj){
		fl.trace(obj+v+'='+obj[v]);
	}
}

traceStructure=function(item, level){
	if(item.libraryItem){
		fl.trace(level+': '+item.libraryItem.name);
	}
	for(var i=0;i<item.childs.length;i++){
		traceStructure(item.childs[i], level+1);
	}
}

deleteEmptyFolders=function(){
	var items=fl.getDocumentDOM().library.items.concat();
	var folders={};
	for(var i=0;i<items.length;i++){
		if(items[i].itemType=='folder'){
			folders[items[i].name]=0;
		}
	}
	for(var i=0;i<items.length;i++){
		if(items[i].itemType!='folder'){
			folders[getFolder(items[i].name)]++;
		}
	}
	for(var v in folders){
		if(!folders[v]){
			if(!v.length){ continue; }
			library.deleteItem(v);
		}
	}
}

//---------------------------------------------START--------------------------
var i,j;
fl.outputPanel.clear();
var doc=fl.getDocumentDOM();

var root=doc.timelines[0];

//----------------------------------counting items before arrange
var countItemsBefore=0;
var items=doc.library.items.concat();
for(i=0;i<items.length;i++){
	if(items[i].itemType!='folder'){
		countItemsBefore++;
	}
}

//----------------------------------creating structure
var structure=getStructure(root);

//----------------------------------creating target library names
prepareNames(['root'], structure, 'root');

//----------------------------------ignored items
var ignoredAsoc={}
for(j=0;j<ignored.length;j++){
	ignoredAsoc[ignored[j]]=true;
}

getAllItems=function(item, arr){
	arr.push(item)
	for(var i=0;i<item.childs.length;i++){
		getAllItems(item.childs[i], arr);
	}
}

var allItems=[]
getAllItems(structure, allItems)

var library=doc.library;


//----------------------------------rearraging
for(i=0;i<allItems.length;i++){
	if(!allItems[i].libraryItem){ continue; }
	if(ignoredAsoc[allItems[i].libraryItem.name.split('/')[0]]){ continue; }
	library.newFolder(getFolder(allItems[i].libName));
	library.moveToFolder(getFolder(allItems[i].libName), allItems[i].libraryItem.name); 
}

//----------------------------------deleting empty folders
if(isDeleteEmptyFolders){
	deleteEmptyFolders()
}

//----------------------------------counting items after arrange
var countItemsAfter=0;
var items=doc.library.items.concat();
for(i=0;i<items.length;i++){
	if(items[i].itemType!='folder'){
		countItemsAfter++;
	}
}
if(countItemsBefore!=countItemsAfter){
	alert('Arrange ERROR! - '+(countItemsBefore-countItemsAfter)+' item(s) are missing. Please do not save this file.')
}else{
	alert('Please use now "File > Save and Compact"');
}
